<template>
<div>

<el-row>

	<el-form :inline="true" :model="form" >

		<el-form-item >
		    <el-input v-model="form.name" placeholder="网格名称"
		    style="width:292px;height:40px;"
		    ></el-input>
		</el-form-item>

		<el-form-item>
		    <el-button type="primary" @click="init"
		    style="width:144px;height:40px;background:#0A85CB;border:1px solid rgba(11, 178, 248, 1);"
		    >查询</el-button>
		</el-form-item>

		<el-form-item>
		    <el-button type="success" @click="addGrid"
		    style="width:144px;height:40px;background:#19A65B;border:1px solid rgba(31, 231, 124, 1);"
		    >添加网格</el-button>
		</el-form-item>

	</el-form>
</el-row>

<el-row >

	<el-table
	    :data="subGrideList.results"
	    :header-cell-style="{
			'background-color': '#f4f4f5',
		    'color': '#616161',    
		}"
	    border
	    style="width: 100%">
	    <el-table-column
	      prop="name"
	      label="网格名称">
	    </el-table-column>
	    <el-table-column
	      prop="company_name"
	      label="所属网格">
	    </el-table-column>
	    <el-table-column
	      prop="type"
	      label="级别">
	    </el-table-column>
	    <el-table-column
	      prop="sort"
	      label="排序">
	    </el-table-column>
	    <el-table-column
	      align="center"
	      label="操作">
	      	<template slot-scope="scope" >
	      		<el-button type="success" size="mini" 
	      		icon="el-icon-edit" circle
	      		@click="editGrid(scope.row)">
	      		</el-button>
	      		<el-button type="danger" size="mini" 
	      		icon="el-icon-delete" circle
	      		@click="deleteGrid(scope.row)">
	      		</el-button>
	      	</template>
	    </el-table-column>
	  </el-table>

</el-row>


<el-row class="text-right mt20 mb20">
	<el-pagination
	  @size-change="handleSizeChange"
	  @current-change="handleCurrentChange"
	  :current-page="pageNo"
	  :page-size="pageSize"
	  layout="total, sizes, prev, pager, next"
	  :total="subGrideList.totalRecord">
	</el-pagination>
</el-row>


<el-dialog
  title="网格信息"
  :visible.sync="grideDialogVisible"
  width="600px">
  
  	<el-form ref="currentGrid" :rules="rules" :model="currentGrid" label-width="130px">

	  <el-form-item label="网格名称：" prop="name" >
	    <el-input v-model="currentGrid.name" placeholder="请输入网格名称" style="width:300px;"></el-input>
	  </el-form-item>

	   <el-form-item label="排序：" prop="sort" >
	    <el-input v-model="currentGrid.sort" placeholder="请输入网格排序" style="width:300px;"></el-input>
	  </el-form-item>

		<el-form-item  v-if="currentGrid.type >= 3" >
			<el-button type="primary" @click="openmap"> 画网格 </el-button>

		</el-form-item>

	  <el-form-item v-else label="地区：" >

	  	<!-- <el-tag
		  v-for="item, index in currentGrid.citys"
		  :key="item.id"
		  type="danger"
		  class="mr10"
		  @close="handleClose(index)"
		  closable>
		  {{item}}
		</el-tag>

		<br> -->
		<el-cascader 
		style="width:300px;"
		:options="districtData"
		:props="props"
		filterable
		change-on-select
		v-model="selectedOptions">
		</el-cascader>

		<!-- <el-button type="primary" @click="addCity">添加</el-button> -->
	  </el-form-item>


	</el-form>


	<el-dialog
      width="70%"
      fullscreen
      :visible.sync="mapVisible"
      append-to-body>

      <div slot="title">

      <el-row>
      	<el-col :span="8">
      		<el-amap-search-box class="search-box" size="mini"
      		:default="'咸阳市'"
      		:search-option="searchOption" 
      		:on-search-result="onSearchResult"></el-amap-search-box>
      	</el-col>
      	<el-col :span="12">
      		<el-button type="primary" @click="saveGrid" class="mt5">保 存</el-button>
      	</el-col>
      </el-row>
      </div>

      <div :style="{width: offsetwidth + 'px', height : offsetheight + 'px'}">
	      <el-amap vid="amapDemo"  
	      :center="center" 
	      :amap-manager="amapManager"  
	      :zoom="zoom" 
	      class="amap-demo">
	      	<el-amap-polygon 
	      	:path="polygon.path"
	      	:editable="polygon.editable"></el-amap-polygon>
	      	<el-amap-polygon v-for="(item, index) in polygon.otherpath" :key="index"
	      	:path="item"
	      	:editable="false"></el-amap-polygon>

	      	<el-amap-polygon 
	      	:fillOpacity="0"
	      	:path="polygon.parentPath"
	      	:editable="false"></el-amap-polygon>
	      </el-amap>
      </div>
		<!-- <span slot="footer" class="dialog-footer">
			<el-button @click="mapVisible = false">取 消</el-button>
			<el-button type="primary" @click="saveGrid">保 存</el-button>
		</span> -->
    </el-dialog>

  <span slot="footer" class="dialog-footer">
    <el-button @click="grideDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save">保 存</el-button>
  </span>
</el-dialog>

</div>
</template>

<script>
import { mapGetters } from 'vuex'
import District from 'ydui-district/dist/gov_province_city_area_id';
import VueAMap from 'vue-amap'
import Vue from 'vue'

let amapManager = new VueAMap.AMapManager();

export default {
	
	name : 'gride',
	
	data () {
		return {
		  	pageNo : 1,
			pageSize : 10,

			gridid : this.obj.id,

			parentGrid : this.obj,

			form : {},
			subGrideList : {},

			currentGrid : {},
			what : '',
			grideDialogVisible : false,

			selectedOptions : [],

			districtData : District,

			props : {
				value : 'v',
				label : 'n',
				children : 'c',
			},

			mapVisible : false,

			zoom: 15,
			center: [],
			//center: [121.5273285, 31.21515044],
			amapManager,

			offsetwidth:document.documentElement.clientWidth - 40,
		  	offsetheight : document.documentElement.clientHeight - 120,

		  	searchOption: {
	            city: '',
	            citylimit: true
	        },

	        polygon: {
				// path: [[121.5273285, 31.21515044], [121.5293285, 31.21515044], [121.5293285, 31.21915044], [121.5273285, 31.21515044]],

				path : [],

				otherpath : [],

				parentPath : [],
				
				editable: true,
	        },


	        rules: {
				name: [
					{ required: true, message: '请输入网格名称', trigger: 'blur' },
				],
				sort: [
					{ required: true, message: '请输入网格排序', trigger: 'blur' },
				],
			},

			defaultGrid : {
				name : '',
			}
		}
	},

	props : {
		obj: {
			type: Object,
			default () {
				return {}
			},
		}
	},

	components : {
		
	},

	computed : {
		...mapGetters({
		  	c : 'center',
		  	city : 'city',
		})
	},

	methods : {
		handleSizeChange (val) {
			this.pageSize = val;
			this.init();
		},

		handleCurrentChange (val) {
			this.pageNo = val;
			this.init();
		},

		init () {
			this.$http({
				fun : 'subGrideList',
				id : this.gridid,
				name : this.form.name,
				pageNo : this.pageNo,
				pageSize : this.pageSize,
				cb : res => {
					console.log('subGrideList');
					console.log(res);
					this.subGrideList = res;
				}
			});
		},


		addGrid (item) {
			this.selectedOptions = [];
			this.currentGrid = {
				parent_id : this.gridid,
				parent_ids : this.parentGrid.parent_ids + this.gridid + ',',
				//citys : [],
				type : parseInt(this.parentGrid.type) + 1,
				sort : 0,
				map : {
					path : [],
					center : this.c,
				},
			};
			this.what = 'add';
			this.grideDialogVisible = true;
			
		},

		editGrid (item) {
			console.log(item);
			this.currentGrid = {
				...item,
				//citys : item.city_name ? item.city_name.split(',') : [],
				map : item.mapinfo ? JSON.parse(item.mapinfo) : {
					path : [],
					center : this.c,
				},
			};
			this.selectedOptions = item.city_name ? item.city_name.split(',') : [];
			this.what = 'edit';
			this.grideDialogVisible = true;
		},

		addCity () {
			this.currentGrid.citys.push(this.selectedOptions.join(''));
		},

		handleClose (index) {
	    	this.currentGrid.citys.splice(index, 1);
	    },

		save () {
			console.log(this.selectedOptions);
			console.log(this.currentGrid.citys);


			this.$refs['currentGrid'].validate((valid) => {
	          if (valid) {
	            let para = {
					fun : 'createGride',
					name : this.currentGrid.name,
					sort : this.currentGrid.sort,
					cb : res => {
						console.log(res);
						this.$message.success('操作成功');
						this.grideDialogVisible = false;
						this.init();
					}
				}

				if(this.what == 'add'){
					para['parent_id'] = this.currentGrid.parent_id;
					para['parent_ids'] = this.currentGrid.parent_ids;
					para['type'] = this.currentGrid.type;
				}else if(this.what == 'edit'){
					para['id'] = this.currentGrid.id;
				}

				console.log(this.currentGrid.type);

				if(parseInt(this.currentGrid.type) > 2){	//镇，村
					para['mapinfo'] = this.currentGrid.mapinfo;
					
				}else{	//市，区/县
					para['city_name'] = this.selectedOptions.join(',');
					para['mapinfo'] = this.selectedOptions[this.selectedOptions.length - 1];
				}

				console.log('para');
				console.log(para);

				this.$http(para);
	          } else {
	            console.log('error submit!!');
	            return false;
	          }
	        });

			
		},

		deleteGrid (item) {

			this.$confirm('此操作将永久删除该网格, 是否继续?', '提示', {
	          confirmButtonText: '确定',
	          cancelButtonText: '取消',
	          type: 'warning'
	        }).then(() => {

	        	this.$http({
	        		fun : 'createGride',
	        		id : item.id,
	        		del_flag : 1,
	        		cb : res => {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.init();
	        		},
	        		err : res => {
	        			this.$message({
							type: 'error',
							message: '删除失败!'
						});
	        		}
	        	});
	          
	        }).catch(() => {
	                   
	        });
		},


		openmap () {
			this.polygon.path = [];
			this.polygon.otherpath = [];
			this.polygon.parentPath = [];

			const parentType = this.parentGrid.type;

			this.$http({
				fun : 'allChildrenList',
				grid_id : this.gridid,
				cb : res => {
					console.log('allChildrenList');
					console.log(res);

					res.forEach(item => {

						if(item.mapinfo != undefined)
						{
							if(item.id == this.gridid){	//父级
								console.log(item.mapinfo);

								if(item.type == '2'){
									AMap.plugin('AMap.DistrictSearch',  () => {
										// 创建行政区查询对象
										var district = new AMap.DistrictSearch({
											// 返回行政区边界坐标等具体信息
											extensions: 'all',
											// 设置查询行政区级别为 区 
											level: 'district'
										})

										district.search(item.mapinfo, (status, result) => {
											console.log(result);
											this.polygon.parentPath = result.districtList[0].boundaries;
											//新增状态，以上级中心点作为中心。
											if(this.currentGrid.id == undefined){
												this.center = [
													result.districtList[0].center.lng, 
													result.districtList[0].center.lat
												];
											}
										})
									})
								}else if(item.type == '3'){
									const obj = JSON.parse(item.mapinfo);
									this.polygon.parentPath = obj.path;

									if(this.currentGrid.id == undefined){
										this.center = obj.center;
									}
								}
							}else if(item.type != parentType 
								  && item.id != this.currentGrid.id){	//其他子级

								const obj = JSON.parse(item.mapinfo);
								this.polygon.otherpath.push(obj.path);
							}
						}
						
					});

					this.polygon.path = this.currentGrid.map.path;
					if(this.currentGrid.id != undefined){
						this.center = this.currentGrid.map.center;
					}


					this.mapVisible = true;
				}
			});
		},

		saveGrid () {
			console.log(this.polygon.path);
			console.log(this.center);
			let arr = [];
			this.polygon.path.forEach(item => {
				arr.push([item.lng, item.lat]);
			});
			this.currentGrid.mapinfo = JSON.stringify({
				center : this.center,
				path : arr,
			});

			this.mapVisible = false;
		},

		onSearchResult(pois) {
          let latSum = 0;
          let lngSum = 0;
          console.log(pois);
          if (pois.length > 0) {
            pois.forEach(poi => {
              let {lng, lat} = poi;
              lngSum += lng;
              latSum += lat;
              //this.markers.push([poi.lng, poi.lat]);
            });
            let center = {
              lng: lngSum / pois.length,
              lat: latSum / pois.length
            };

            console.log(center);
            this.center = [center.lng, center.lat];

            this.polygon.path = [
            	[center.lng, center.lat],
            	[center.lng + 0.002, center.lat],
            	[center.lng + 0.002, center.lat + 0.004],
            	[center.lng, center.lat],
            ];
          }
        },


        start () {
        	this.polygon.editable = !this.polygon.editable;
        },
	},

	watch : {
	    
	},

	mounted () {
		this.init();

		console.log(this.districtData);

		this.center = this.c;
		this.searchOption.city = this.city;
	},

}
</script>

<style scoped>

</style>
